<template>
  <div class="data-handle">
    <el-form ref="queryForm" class="query-form" :model="queryParams" :inline="true" size="small">
      <el-form-item label="项目" prop="date">
        <el-select style="width: 150px;" v-model="projectId" @change="onAppChange">
          <el-option v-for="item in permission_projectList" :value="item.app_id" :label="item.name"
            :key="item.app_id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择时间" prop="date" class="big-query">
        <date-range v-model="queryParams.date"/>
      </el-form-item>
      <el-form-item label="选择版本" prop="version">
        <version-select ref="versionSelect" :selOptions="versionOpts" v-model="queryParams.version"></version-select>
      </el-form-item>
      <el-form-item label="反馈来源" prop="come_from" class="small-query">
        <el-select v-model="queryParams.come_from" placeholder="请选择">
          <el-option label="全部" :value="null"></el-option>
          <el-option v-for="item in comeFromMap" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="渠道" prop="union">
        <select-check-box  v-model="queryParams.union"
          :selOptions="channelOpts"
          :props="{value:'channel_id',label:'name'}"
          doubleColumn
          filterable
          checkAllLabel="全部渠道">
        </select-check-box>
      </el-form-item>
      <el-form-item label="反馈内容" prop="have_content" class="small-query">
        <el-select v-model="queryParams.have_content" placeholder="请选择">
          <el-option label="全部" :value="null"></el-option>
          <el-option label="有内容" :value="1"></el-option>
          <el-option label="无内容" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="反馈内容" prop="param" class="big-query">
        <el-input v-model="queryParams.param" placeholder="请输入" clearable @keyup.enter="getList(true)">
          <el-button type="primary" slot="append" @click="getList(true)">搜索</el-button>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="success"
          :loading="exportLoading"
          @click="exportExcel">导出全部</el-button>
      </el-form-item>
    </el-form>
    <div class="search-box">
      <div class="add">
        <el-button type="primary" icon="el-icon-plus" @click="feedback">录入反馈</el-button>
      </div>
    </div>
    <el-table v-loading="tableLoading" :data="tableData" style="width: 100%">
      <el-table-column label="反馈详情" align="center" class-name="c1">
        <el-table-column label="时间" prop="date" align="center" max-width="120px" class-name="c2">
          <template #default="{ row }">
            {{ row.create_time | parseTime }}
          </template>
        </el-table-column>
        <el-table-column label="版本" prop="version" align="center" width="100px" class-name="c2">
        </el-table-column>
        <el-table-column label="反馈来源" prop="come_from" align="center" class-name="c2" width="100px"
          show-overflow-tooltip>
          <template #default="{ row }">
            {{ getComeFromLabel(row.come_from) }}
          </template>
        </el-table-column>
        <el-table-column
            label="渠道"
            prop="union"
            align="center"
            width="100"
            class-name="c2"
            show-overflow-tooltip
          >
          </el-table-column>
        <el-table-column label="反馈内容" prop="content" min-width="160" align="center" class-name="c2">
        </el-table-column>
        <el-table-column label="附件" align="center" width="60" class-name="c2">
          <template #default="{ row }">
            <el-popover width="300" trigger="hover" popper-class="affix-popover" :key="row.id">
              <div class="affix-box">
                <div class="img-list um-scroll">
                  <div class="img-list_item" v-for="(it, i) in row.imgs" :key="i">
                    <img :src="it.location" alt="" />
                  </div>
                </div>
              </div>
              <i v-show="Array.isArray(row.imgs) && row.imgs.length" slot="reference"
                class="el-icon-picture-outline"></i>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="更多" align="center" class-name="c2">
          <template #default="{ row }">
            <el-button type="primary" size="mini" @click="detailLayer(row)">查看</el-button>
            <p class="text">{{ row.contact }}</p>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="反馈标签化" align="center" class-name="c3">
        <el-table-column label="所属模块" align="center" class-name="c4">
          <el-table-column align="center" class-name="c5" min-width="140px">
            <template #header>
              <select-check-box size="small" filterable v-model="queryParams.mod_id" :selOptions="moduleOpts" :props="{
      label: 'mod_name',
      value: 'mod_id'
    }" checkAllLabel="全部模块" @change="moduleFilter" />
            </template>
            <template #default="{ row }">
              <el-select v-model="row.module" multiple size="mini" clearable @change="moduleChange($event, row)">
                <el-option v-for="item in moduleOpts.slice(1)" :key="item.mod_id" :label="item.mod_name"
                  :value="item.mod_id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="内容标签" align="center" class-name="c4">
          <el-table-column align="center" class-name="c5" min-width="140px">
            <template #header>
              <el-select v-model="queryParams.label_id" size="small" filterable multiple collapse-tags
                placeholder="全部标签" popper-class="group-select" @change="getList(true)">
                <el-option-group v-for="group in tagOpts" :label="group.mod_name" :key="group.mod_id">
                  <el-option v-for="item in group.options" :key="item.label_id" :label="item.label_name"
                    :value="item.label_id">
                  </el-option>
                </el-option-group>
              </el-select>
            </template>
            <template #default="{ row }">
              <el-select v-model="row.label" multiple filterable size="mini" clearable
                :disabled="!Array.isArray(row.module) || !row.module.length" @change="saveModify(row)">
                <el-option-group v-for="group in row.tagOpts" :label="group.mod_name" :key="group.mod_id">
                  <el-option v-for="item in group.options" :key="item.label_id" :label="item.label_name"
                    :value="item.label_id">
                  </el-option>
                </el-option-group>
              </el-select>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table-column>
      <el-table-column label="反馈处理" align="center" class-name="c6">
        <el-table-column label="处理小组" align="center" class-name="c7">
          <el-table-column align="center" class-name="c8" min-width="110px">
            <template #header>
              <select-check-box filterable size="small" v-model="queryParams.group_id" :selOptions="groupOpts" :props="{
      label: 'group_name',
      value: 'group_id'
    }" checkAllLabel="全部处理小组" @change="groupFilter" />
            </template>
            <template #default="{ row }">
              <el-select v-model="row.handle_group" size="mini" clearable @change="groupChange($event, row)">
                <el-option v-for="item in groupOpts.slice(1)" :key="item.group_id" :label="item.group_name"
                  :value="item.group_id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column label="处理结果" align="center" class-name="c7">
          <el-table-column align="center" class-name="c8" min-width="110px">
            <template #header>
              <el-select v-model="queryParams.result_id" size="small" multiple collapse-tags placeholder="全部结果"
                popper-class="group-select" @change="getList(true)">
                <el-option-group v-for="group in resOpts" :label="group.group_name" :key="group.group_id">
                  <el-option v-for="item in group.options" :key="item.result_id" :label="item.result_name"
                    :value="item.result_id">
                  </el-option>
                </el-option-group>
              </el-select>
            </template>
            <template #default="{ row }">
              <el-select v-model="row.result" clearable size="mini" :disabled="!row.handle_group"
                @change="saveModify(row)">
                <el-option v-for="item in row.resOpts" :key="item.result_id" :label="item.result_name"
                  :value="item.result_id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="反馈状态" align="center" class-name="c7">
          <el-table-column align="center" class-name="c8" width="100px">
            <template #header>
              <el-select v-model="queryParams.status" size="small" @change="getList(true)">
                <el-option label="全部" value=""> </el-option>
                <el-option v-for="item in statusOpts" :key="item.status_id" :label="item.status_name"
                  :value="item.status_id">
                </el-option>
              </el-select>
            </template>
            <template #default="{ row }">
              <span class="status" :class="getStatusClass(row.status)">{{
      row.status
      | translateToName(statusOpts, 'status_id', 'status_name')
    }}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="备注" align="center" class-name="c7" min-width="100px">
          <template #default="{ row }">
            <el-input v-model="row.remark" type="textarea" placeholder="请输入" :rows="2" size="mini"
              @blur="saveModify(row)"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="录入mantis" align="center" class-name="c7" width="100px">
          <template #default="{ row }">
            <el-button type="text" @click="recordBug(row)">{{ row.isrecord ? '再次' : '' }}录入</el-button>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
    <Pagination :total="total" :page.sync="queryParams.page_index" :limit.sync="queryParams.page_size"
      @pagination="getList" />
    <el-dialog title="录入MANTIS" width="600px" :visible.sync="bugShow">
      <el-form ref="bugForm" :model="bugForm">
        <el-form-item label="BUG描述：" prop="content" :rules="{ required: true, message: '请输入bug内容描述' }">
          <el-input type="textarea" :rows="6" v-model="bugForm.content" placeholder="请输入bug内容描述"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="btns">
          <el-button type="info" @click="bugShow = false">取消</el-button>
          <el-button type="primary" @click="saveRecord">录入</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="查看" top="10vh" width="800px" :visible.sync="detail.show">
      <record-detail :key="detail.show" :detail="detail.data" :statusOpts="statusOpts" />
    </el-dialog>
    <add-record :visible.sync="addLayerShow" :projectId="projectId" :groupOpts="groupOpts" :versionOpts="versionOpts"
      @update="getList(true)" />
  </div>
</template>

<script type="text/javascript">
import axios from 'axios'
import { mapGetters } from 'vuex'
import { getFbList, addToMantis, modifyFb, createExportFeedTask, queryExportFeedTask } from '@/api/feedback/index'
import { COME_FROM } from '../constant'
import { parseTime, downloadExportUrl } from '@/utils'
import * as resource from '../resource'
import RecordDetail from './components/RecordDetail.vue'
import AddRecord from './components/AddRecord.vue'
import DateRange from '../dataReport/components/dateRange.vue'
import { getChannelByAppId } from '@/api/system/channel'
import { getVersionTree } from '@/api'
const dateFmt = '{y}-{m}-{d}'
export default {
  name: 'DataHandle',
  components: { RecordDetail, AddRecord, DateRange },
  props: {},
  data () {
    const d = new Date()
    const end = parseTime(d, dateFmt)
    const start = parseTime(d.setDate(d.getDate() - 29), dateFmt)
    return {
      projectId: null,
      tableLoading: false,
      exportLoading: false,
      comeFromMap: COME_FROM,
      queryParams: {
        date: [start, end],
        version: '',
        come_from: null,
        have_content: null,
        param: '',
        status: '',
        union: [],
        mod_id: [],
        label_id: [],
        group_id: [],
        result_id: [],
        page_index: 1,
        page_size: 10,
        detail: true
      },
      total: 0,
      tableData: [],
      bugShow: false,
      bugForm: {},
      channelOpts: [],
      versionOpts: [],
      moduleOpts: [],
      tagList: [], // 标签列表
      tagOpts: [], // 标签筛选选项
      groupOpts: [],
      resList: [],
      resOpts: [],
      statusOpts: [],
      addLayerShow: false,
      detail: {
        show: false,
        data: {}
      },
      tagOptions: [],
      resOptions: []
    }
  },
  async mounted () {
    await this.getChannels()
    if (this.permission_projectList.length) {
      this.projectId = this.permission_projectList[0].app_id
    }
    this.onAppChange(this.projectId)
    this.getList()
  },
  methods: {
    async init () {
      getVersionTree({ app_id: this.projectId, is_test: false })
        .then(res => {
          let list = res.data || []
          this.versionOpts = list
        })
      await axios
        .all([resource.getModuleList({ pro_id: this.projectId }), resource.getGroupList({ pro_id: this.projectId }), resource.getTagList({ pro_id: this.projectId }, false), resource.getResList({ pro_id: this.projectId }, false), resource.getStatusList(this.projectId)])
        .then(
          axios.spread((res1, res2, res3, res4, res5) => {
            res1.unshift({
              mod_name: '未分配模块',
              mod_id: 0
            })
            this.moduleOpts = res1
            res2.unshift({
              group_id: 0,
              group_name: '未设置处理小组'
            })
            this.groupOpts = res2
            this.tagList = res3
            this.tagOptions = this.getTagOptions()
            this.moduleChange()
            this.resList = res4
            this.resOptions = this.getResOptions()
            this.groupChange()
            this.statusOpts = res5
          })
        )
    },
    getChannels () {
      const list = this.permission_projectList.map(item => item.app_id)
      return getChannelByAppId({
        app_ids: list.join()
      }).then(res => {
        this.channelList = res.data.list.map(item => {
          item.name = `${item.name}(${item.channel_id})`
          return item
        })
      })
    },
    onAppChange () {
      this.channelOpts = this.channelList.filter(item1 => item1.app_id === this.projectId)
      this.init()
    },
    async moduleChange (modId, row) {
      const has = modId && modId.length
      const isVm = !row
      if (isVm) row = this
      row.tagOpts = has ? this.tagOptions.filter(t => modId.includes(t.mod_id)) : this.tagOptions
      const labeIds = has ? row.tagOpts.reduce((arr, t) => {
        arr.push(...t.options.map(t => t.label_id))
        return arr
      }, []) : []
      if (isVm) {
        row.queryParams.label_id = row.queryParams.label_id.filter(id => labeIds.includes(id))
      } else {
        row.label = row.label.filter(id => labeIds.includes(id))
        this.saveModify(row)
      }
    },
    async groupChange (groupId, row) {
      if (!row) {
        const has = groupId && groupId.length
        this.resOpts = has ? this.resOptions.filter(t => groupId.includes(t.group_id)) : this.resOptions
        const resultds = has ? this.resOpts.reduce((arr, t) => {
          arr.push(...t.options.map(t => t.result_id))
          return arr
        }, []) : []
        this.queryParams.result_id = this.queryParams.result_id.filter(id => resultds.includes(id))
      } else {
        row.result = ''
        row.resOpts = this.resList.filter(t => t.gro_id === groupId)
        this.saveModify(row)
      }
    },
    moduleFilter () {
      this.moduleChange.apply(this, arguments)
      this.getList(true)
    },
    groupFilter () {
      this.groupChange.apply(this, arguments)
      this.getList(true)
    },
    getQueryParams () {
      const params = {}
      for (const key in this.queryParams) {
        let val = this.queryParams[key]
        if (key === 'date') {
          params.start_time = val[0] + ' 00:00:00'
          params.end_time = val[1] + ' 23:59:59'
        } else {
          params[key] = Array.isArray(val) ? val.join(',') : val
        }
      }
      if (this.queryParams.have_content) {
        params.is_have_content = this.queryParams.have_content === 1
      }
      params.pro_id = this.projectId
      return params
    },
    getList (refresh = false) {
      refresh === true && (this.queryParams.page_index = 1)
      const params = this.getQueryParams()
      this.tableLoading = true
      return getFbList(params)
        .then(res => {
          this.tableData =
            (res.data.list || []).map(t => {
              const attachment = t.attachment || []
              const module = t.module || []
              const group = t.handle_group
              return {
                ...t,
                module,
                label: (t.label || []).map(t => t.label_id),
                handle_group: group || '',
                result: t.result || '',
                imgs: attachment.filter(t => t.type === 1),
                tagOpts: module.length
                  ? this.tagOptions.filter(t => module.includes(t.mod_id))
                  : [],
                resOpts: this.resOptions.find(t => group === t.group_id)?.options || []
              }
            }) || []
          this.total = res.data.count
          this.tableLoading = false
        })
        .catch(() => {
          this.tableLoading = false
        })
    },
    saveModify (row) {
      const {
        id,
        module,
        label,
        handle_group: handleGroup,
        result,

        remark
      } = row
      const params = {
        feedback_id: id,
        group: handleGroup || 0,
        result: result || 0,
        note: remark
      }
      if (Array.isArray(module)) params.module = module
      if (Array.isArray(label)) params.label = label.map(id => ({ id }))
      let status = row.status
      if (result) {
        status = 3
      } else if (handleGroup) {
        status = 2
      } else {
        status = 1
      }
      row.status = params.status = status
      modifyFb(params)
    },
    feedback () {
      this.addLayerShow = true
    },
    detailLayer (row) {
      const module = row.module || []
      const moduleName = module.reduce((arr, modId) => {
        const item = this.moduleOpts.find(it => it.mod_id === modId)
        item && arr.push(item.mod_name)
        return arr
      }, [])
      const label = row.label || []
      const labelName = label.reduce((arr, labelId) => {
        const item = this.tagList.find(it => it.label_id === labelId)
        item && arr.push(item.label_name)
        return arr
      }, [])
      const groupName = this.groupOpts.find(
        t => t.group_id === row.handle_group
      )?.group_name
      const resultName = row.resOpts.find(
        t => t.result_id === row.result
      )?.result_name
      const inputGroup = this.groupOpts.find(
        t => t.group_id === row.input_group
      )?.group_name
      this.detail.data = {
        ...row,
        moduleName,
        labelName,
        groupName,
        resultName,
        inputGroup
      }
      this.detail.show = true
    },
    recordBug (row) {
      this.bugForm = {
        feedback_id: row.feedback_id,
        content: row.content
      }
      this.bugShow = true
    },
    saveRecord () {
      this.$refs.bugForm.validate(valid => {
        if (valid) {
          addToMantis(this.bugForm).then(res => {
            if (res.code === 200) {
              this.$message.success('录入成功！')
              this.bugShow = false
            }
          })
        }
      })
    },
    getStatusClass (val) {
      const map = {
        1: 'unProcess',
        2: 'processing',
        3: 'procesed'
      }
      return map[val]
    },
    getComeFromLabel (val) {
      const obj = this.comeFromMap.find(item => item.value === val) || {}
      return obj.label || ''
    },
    getTagOptions () {
      const map = this.tagList.reduce((map, it) => {
        if (!map[it.mod_id]) {
          map[it.mod_id] = [it]
        } else {
          map[it.mod_id].push(it)
        }
        return map
      }, {})
      const list = this.moduleOpts.reduce((arr, item) => {
        const options = map[item.mod_id]
        options && arr.push({
          mod_id: item.mod_id,
          mod_name: item.mod_name,
          mod_idx: item.mod_idx,
          options
        })
        return arr
      }, [])
      list.unshift({
        mod_id: -1,
        mod_name: '未分组',
        mod_idx: '',
        options: [
          {
            label_id: 0,
            label_name: '无内容标签'
          }
        ]
      })
      return list
    },
    getResOptions () {
      const map = this.resList.reduce((map, it) => {
        if (!map[it.gro_id]) {
          map[it.gro_id] = [it]
        } else {
          map[it.gro_id].push(it)
        }
        return map
      }, {})
      const list = this.groupOpts.reduce((arr, item) => {
        const options = map[item.group_id]
        options && arr.push({
          group_id: item.group_id,
          group_name: item.group_name,
          group_idx: item.group_idx,
          options
        })
        return arr
      }, [])
      list.unshift({
        group_id: -1,
        group_name: '未分组',
        group_idx: '',
        options: [
          {
            result_id: -1,
            result_name: '无结果标签'
          }
        ]
      })
      return list
    },
    /** 点击-全部导出 */
    exportExcel () {
      this.exportLoading = true
      const params = this.getQueryParams()
      delete params.page_index
      delete params.page_size
      createExportFeedTask({ filter: params })
        .then(response => {
          const { task_id } = response.data || {}
          if (task_id) {
            this.queryExportTask(task_id, () => {
              this.exportLoading = false
            })
          } else {
            this.$message.error('导出订单任务创建失败')
            this.exportLoading = false
          }
        })
        .catch(e => {
          this.exportLoading = false
        })
    },
    /** 查询导出订单任务结果 */
    queryExportTask (task_id, func) {
      queryExportFeedTask({ task_id })
        .then(response => {
          if (response.data?.status === 'finished') {
            downloadExportUrl(response.data.file_url)
            typeof func === 'function' && func(true)
          } else {
            setTimeout(() => {
              this.queryExportTask(task_id, func)
            }, 1000)
          }
        })
        .catch(() => {
          typeof func === 'function' && func(false)
        })
    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList'])
  }
}
</script>

<style lang="scss" scoped>
.data-handle {
  .search-box {
    display: flex;
    margin-bottom: 10px;

    .search-item {
      display: flex;
      align-items: center;
      margin-right: 20px;

      .label {
        flex: 70px 0 0;
      }
    }

    .add {
      flex: 1;
      text-align: right;
    }
  }

  .el-table {
    /deep/ thead {
      th {
        color: #333;

        &.c1 {
          background-color: rgba(129, 211, 248, 1);
        }

        &.c2 {
          background-color: rgba(129, 211, 248, 0.7);
        }

        &.c3 {
          background-color: rgba(147, 198, 68, 1);
        }

        &.c4 {
          background-color: rgba(147, 198, 68, 0.7);
        }

        &.c5 {
          background-color: rgba(147, 198, 68, 0.6);
        }

        &.c6 {
          background-color: rgba(57, 193, 136, 1);
        }

        &.c7 {
          background-color: rgba(57, 193, 136, 0.7);
        }

        &.c8 {
          background-color: rgba(57, 193, 136, 0.6);
        }
      }
    }

    .status {
      display: inline-block;
      color: #fff;
      font-size: 12px;
      padding: 4px 8px;
      line-height: normal;
      border-radius: 30px;

      &.unProcess {
        background-color: #bbb;
      }

      &.processing {
        background-color: #f59a23;
      }

      &.procesed {
        background-color: #6aaa03;
      }
    }

    .el-icon-picture-outline {
      font-size: 16px;
    }
  }

  .el-select {
    /deep/ .el-select__tags {
      .el-tag {
        height: auto;
        text-align: left;
      }

      .el-select__tags-text {
        // display: inline-block;
        // max-width: 50px;
        // overflow: hidden;
        white-space: normal;
      }

      .el-tag__close {
        top: -6px;
        display: none;
      }
    }

    /deep/ .el-input .el-input__inner {
      padding-left: 10px;
      padding-right: 26px;
    }
  }

  .pagination-container {
    padding-bottom: 0;
  }

  .text {
    margin-top: 4px;
  }

}
</style>
<style lang="scss">
.el-popover.el-popper.affix-popover {
  .img-list {
    max-width: 300px;
    max-height: 600px;
  }

  .img-list_item {
    margin-bottom: 10px;

    &*:last-of-type {
      margin-bottom: 0;
    }

    img {
      width: 100%;
      object-fit: contain;
    }
  }
}

/* .el-select-dropdown {
  .el-select-group__title {
    color: #666;
    font-size: 14px;
    font-weight: bold;
  }
} */
</style>
